package com.longrise.android.byjk.plugins.tabfirst;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.webkit.WebView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalInfoActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.caculate.BitmapCaculate;
import com.longrise.android.byjk.plugins.request.AppBaseRequest;
import com.longrise.android.byjk.plugins.request.AppBaseResult;
import com.longrise.android.byjk.plugins.request.ChangeInforRequest;
import com.longrise.android.byjk.plugins.request.RequestThread;
import com.longrise.android.byjk.plugins.tabthird.personal.ChangeNormalWallActivity;
import com.longrise.android.byjk.plugins.tabthird.personal.ChangeSeniorWallActivity;
import com.longrise.android.byjk.plugins.tabthird.personal.ChangeWallEvent;
import com.longrise.android.byjk.utils.GetWebUrlHelper;
import com.longrise.android.byjk.widget.crop.Crop;
import com.longrise.android.ui.dialog.ActionSheetDialog;
import com.longrise.common.base.web.BaseWebActivity;
import com.longrise.common.base.web.BaseWebBridge;
import com.longrise.common.base.web.BaseWebClient;
import com.longrise.common.permission.PermissionUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.FolderConstants;
import com.longrise.common.utils.NetUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import static com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalPresenter.TOCAMERA;
import static com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalPresenter.TOGALLERY;

/**
 * Created by Administrator on 2018/3/12.
 * 电子名片
 */

public class PersonalShowActivity2 extends BaseWebActivity{


    public static final String TAG = "PersonalShowActivity2";
    private WebView mWv;
    private final int STARTA_EDIT_REQUEST = 102;
    private final int STARTA_SENIOR_WALL = 103;
    private final int STARTA_NORMAL_WALL = 104;
    private File mImageFile;
    private Uri mImageUri;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_personal_show2;
    }

    @Override
    public WebView getWebView() {
        return mWv;
    }

    @Override
    public void init() {
        mWv = (WebView) findViewById(R.id.wv_person_show);
        setWebTitle(getString(R.string.person_vcard));
        setToolbarRightIvTitle(R.drawable.by_ic_share);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        request();
    }

    public void request(){
        GetWebUrlHelper.getWebUrl(GetWebUrlHelper.GRZY, new GetWebUrlHelper.OnGetWebUrlResultListener() {
            @Override
            public void onSuccess(String url) {
                loadUrl(url);
            }

            @Override
            public void onError(String errormsg) {
                showToast(errormsg);
            }
        });
    }


    @Override
    public BaseWebBridge getwebBridge() {
        return new PersonShowBridge2(this, mRxmanager);
    }

    @Override
    public BaseWebClient getWebClient() {
        return null;
    }

    public void startActivity(){
        Intent intent = new Intent(PersonalShowActivity2.this, PersonalInfoActivity.class);
        startActivityForResult(intent, STARTA_EDIT_REQUEST);
    }


    @Override
    public void onToolbarRightIvClick() {
        super.onToolbarRightIvClick();
        mWv.loadUrl("javascript:$_$.shareurl()");
    }

    public void jump2BackWallActivity(){
        String isecardvip = UserInfor.getInstance().getIsecardvip();
        if("0".equals(isecardvip)){   //免费用户
            Intent intent1 = new Intent(PersonalShowActivity2.this, ChangeNormalWallActivity.class);
            startActivity(intent1);
        }else if("1".equals(isecardvip)){    //付费用户
            Intent intent2 = new Intent(PersonalShowActivity2.this, ChangeSeniorWallActivity.class);
            startActivity(intent2);
        }
    }

    public void uploadUserImg(){
        getCameraPermission();
    }

    private void getCameraPermission() {
        PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.CAMERA, getString(R.string.camera_permission), getString(R.string.camera_permission_hint), new PermissionUtil.PermissionCallBack() {
            @Override
            public void onSuccess() {
                changeHeadIcon();
            }

            @Override
            public void onDenied() {

            }
        });
    }

    private void changeHeadIcon() {
        new ActionSheetDialog(this).builder().setCancelable(false).setCanceledOnTouchOutside(false).addSheetItem(getString(R.string.takecamera), ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                toCamera(PersonalShowActivity2.this);
            }
        }).addSheetItem(getString(R.string.picture_options_selceter), ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                toGallery(PersonalShowActivity2.this);
            }
        }).setCancelColor(ActionSheetDialog.SheetItemColor.BlueDeep).setOnCancelListener(new ActionSheetDialog.OncancelListener() {
            @Override
            public void onCancel() {

            }
        }).show();
    }

    public void toCamera(Context context) {
        this.mContext = context;
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
            mImageFile = new File(createPicFile(), System.currentTimeMillis() + ".jpg");
//            Uri mOutPutFileUri = Uri.fromFile(mImageFile);
            Uri mOutPutFileUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mOutPutFileUri = FileProvider.getUriForFile(mContext, FolderConstants.FILE_PROVIDER, mImageFile);
            } else {
                mOutPutFileUri = Uri.fromFile(mImageFile);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutPutFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, TOCAMERA);
        } else {
        }
    }

    public void toGallery(Context context) {
        this.mContext = context;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, TOGALLERY);
    }

    private File createPicFile() {
        File path1 = new File(FolderConstants.BB_CAMERA_DIR);
        if (!path1.exists()) {
            path1.mkdirs();
        }
        return path1;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        boolean isReset = data != null ? data.getBooleanExtra("key", false) : false;
        switch (requestCode) {
            case TOCAMERA:
                if (mImageFile != null && mImageFile.exists()) {
                    beginCrop(Uri.fromFile(mImageFile));
                }
                break;

            case TOGALLERY:
                if (data != null) {
                    Uri uri = data.getData();
                    beginCrop(uri);
                }
                break;

            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;

            case STARTA_EDIT_REQUEST:
                if (NetUtil.checkNetEnable()) {
                    request();
                }
                break;
            default:
                break;
        }
    }

    private void beginCrop(Uri source) {
        createPicFile();
        File file = new File(FolderConstants.BB_CAMERA_DIR, "cropped.jpg");
        if (file.exists()) {
            file.delete();
        }
        Uri destination = Uri.fromFile(file);
        Crop.of(source, destination).withMaxSize(480, 640).asSquare().start(((PersonalShowActivity2) mContext));
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            mImageUri = Crop.getOutput(result);
            Bitmap bitmap = BitmapCaculate.decodeBitmapFromLocalPath(mImageUri.getPath(), 480, 640);
            String bitmapBase64 = BitmapCaculate.bitmapToBase64(bitmap);
            uploadUserHeadIcon(bitmapBase64);
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            DZZWTools.showToast(mContext, mContext.getString(R.string.getlocal_uri_icon), Toast.LENGTH_SHORT);
        }
    }


    private void uploadUserHeadIcon(String base64) {
        Bundle bundle = new Bundle();
        bundle.putString("bycardstr", base64);
        commit("insh_user_photo", bundle);
    }

    private void commit(String api, Bundle bundle) {
        onLoading();
        ChangeInforRequest changeInforRequest = new ChangeInforRequest(new UserIconResult1());
        changeInforRequest.setApi(api);
        RequestThread requestThread = new RequestThread(changeInforRequest);
        requestThread.request(mContext, AppBaseRequest.APP_REQUEST_TAG, bundle);
    }

    private class UserIconResult1 implements AppBaseResult {

        @Override
        public void onSuccess(Object result) {
            //将本地headicon重新设置 返回图片存放的地址重新设置本地headicon
            EntityBean bean = (EntityBean) result;
            if (bean != null && bean.getInt("resultstate") == 1) {
                request();
            }
        }

        @Override
        public void onFailed(String errorLog) {
            showToast(mContext.getString(R.string.upload_icon_faile));

        }

        @Override
        public void onFinish() {
            showContentPage();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeSkin(ChangeWallEvent event) {
        if(event.isRefresh()){
            request();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
